<template>
	<view class="container">
		
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 父分类选择 -->
			<view class="input-container">
				<view class="label-text">父分类（可选）</view>
				<view class="picker-container" @click="showParentPicker = true">
					<text class="picker-text" :class="{ placeholder: !selectedParent }">
						{{ selectedParent ? getCategoryPath(selectedParent) : '请选择父分类（不选则为顶级分类）' }}
					</text>
					<text class="picker-arrow">▼</text>
				</view>
			</view>
			
			<!-- 输入框 -->
			<view class="input-container">
				<view class="label-text">分类名称</view>
				<input 
					class="category-input"
					type="text"
					placeholder="请输入新的商品分类(最长10个汉字)"
					v-model="categoryName"
					maxlength="10"
				/>
			</view>
		</view>
		
		<!-- 父分类选择器 -->
		<picker
			v-if="categoryOptions.length > 0"
			mode="selector"
			:range="categoryOptions"
			range-key="label"
			:value="parentIndex"
			@change="onParentChange"
			:disabled="false"
			style="display: none;"
		>
			<view v-if="showParentPicker"></view>
		</picker>
		
		<!-- 自定义选择器弹窗 -->
		<view v-if="showParentPicker" class="picker-modal" @click.stop="showParentPicker = false">
			<view class="picker-content" @click.stop>
				<view class="picker-header">
					<text class="picker-title">选择父分类</text>
					<text class="picker-close" @click.stop="showParentPicker = false">×</text>
				</view>
				<view class="picker-body">
					<view 
						class="picker-option" 
						:class="{ active: !selectedParent }"
						@click="selectParent(null)"
					>
						<text>顶级分类（无父分类）</text>
					</view>
					<view 
						v-for="option in categoryOptions"
						:key="option.value"
						class="picker-option"
						:class="{ active: selectedParent === option.value }"
						@click="selectParent(option.value)"
					>
						<text>{{ option.label }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 添加按钮 - 固定到最下方 -->
		<view class="button-container">
			<button 
				class="add-button"
				@click="addCategory"
			>
				添加
			</button>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			categoryName: '',
			selectedParent: null, // 选中的父分类ID
			showParentPicker: false,
			categories: [], // 分类列表
			categoryOptions: [] // 选择器选项
		}
	},
	onLoad(options) {
		// 接收传递过来的分类数据
		if (options.categories) {
			try {
				this.categories = JSON.parse(decodeURIComponent(options.categories))
				this.buildCategoryOptions()
				
				// 如果传递了 parentId 参数，自动选中该父分类
				if (options.parentId) {
					const parentId = decodeURIComponent(options.parentId)
					// 验证父分类是否存在
					if (this.findCategoryById(this.categories, parentId)) {
						this.selectedParent = parentId
					}
				}
			} catch (e) {
				console.error('解析分类数据失败:', e)
			}
		} else if (options.parentId) {
			// 如果没有分类数据但有 parentId，也先设置（如果后续加载了分类数据，会自动选中）
			this.selectedParent = decodeURIComponent(options.parentId)
		}
	},
	methods: {
		// 在分类树中查找指定ID的分类
		findCategoryById(categories, categoryId) {
			for (const category of categories) {
				if (category.id === categoryId) {
					return category
				}
				if (category.children && category.children.length > 0) {
					const found = this.findCategoryById(category.children, categoryId)
					if (found) {
						return found
					}
				}
			}
			return null
		},
		
		// 构建分类选项（从扁平数据构建树形结构，然后扁平化显示）
		buildCategoryOptions() {
			// 将扁平数据转换为树形结构
			const tree = this.buildTree(this.categories)
			this.categoryOptions = []
			this.flattenCategories(tree, 0, '')
			
			// 如果之前设置了 selectedParent，在构建选项后再次验证并选中
			if (this.selectedParent) {
				const parent = this.findCategoryById(tree, this.selectedParent)
				if (!parent) {
					// 如果找不到，清空选择
					this.selectedParent = null
				}
			}
		},
		
		// 将扁平数据转换为树形结构
		buildTree(list) {
			const map = {}
			list.forEach(item => {
				item.children = []
				map[item.id] = item
			})
			
			const tree = []
			list.forEach(item => {
				// 使用 parentCode 字段
				const parentCode = item.parentCode || item.parentId || item.parent_id || '0'
				
				if (parentCode === '0' || parentCode === 0 || !parentCode) {
					tree.push(item)
				} else {
					const parent = map[parentCode]
					if (parent) {
						if (!parent.children) {
							parent.children = []
						}
						parent.children.push(item)
					} else {
						tree.push(item)
					}
				}
			})
			
			return tree
		},
		
		// 递归扁平化分类树（用于显示）
		flattenCategories(categories, level, prefix) {
			categories.forEach(category => {
				const label = prefix + category.name
				this.categoryOptions.push({
					label: label,
					value: category.id,
					name: category.name
				})
				
				// 递归处理子分类
				if (category.children && category.children.length > 0) {
					this.flattenCategories(category.children, level + 1, prefix + '　')
				}
			})
		},
		
		// 获取分类路径
		getCategoryPath(categoryId) {
			// 先构建树
			const tree = this.buildTree(this.categories)
			
			const findPath = (categories, targetId, path = []) => {
				for (const category of categories) {
					if (category.id === categoryId) {
						return [...path, category.name].join(' > ')
					}
					if (category.children && category.children.length > 0) {
						const found = findPath(category.children, targetId, [...path, category.name])
						if (found) {
							return found
						}
					}
				}
				return null
			}
			
			return findPath(tree, categoryId) || ''
		},
		
		// 选择父分类
		selectParent(parentId) {
			this.selectedParent = parentId
			this.showParentPicker = false
		},
		
		// 选择器变化事件
		onParentChange(e) {
			const index = e.detail.value
			if (index === 0) {
				this.selectedParent = null
			} else {
				this.selectedParent = this.categoryOptions[index - 1].value
			}
		},
		
		addCategory() {
			if (!this.categoryName.trim()) {
				uni.showToast({
					title: '请输入分类名称',
					icon: 'none'
				})
				return
			}
			
			// 调用API添加分类
			const params = {
				name: this.categoryName.trim(),
			}
			
			// 如果选择了父分类，添加 parentCode；否则设置为 "0" 表示顶级分类
			if (this.selectedParent) {
				params.parentCode = this.selectedParent
			} else {
				params.parentCode = "0"
			}
			
			uni.showLoading({
				title: '添加中...'
			})
			
			this.$u.api.productCategory.save(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result === 'true') {
					uni.showToast({
						title: res.message || '添加成功',
						icon: 'success'
					})
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.message || '添加失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('添加分类失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			})
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	position: relative;
}


/* 主要内容区域 */
.main-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 60px 30px 120px 30px;
	gap: 40px;
}

/* 输入框容器 */
.input-container {
	width: 100%;
	margin-bottom: 20px;
}

.label-text {
	color: #333333;
	font-size: 14px;
	margin-bottom: 8px;
	font-weight: 500;
}

.picker-container {
	width: 100%;
	height: 50px;
	background-color: #f5f5f5;
	border-radius: 8px;
	padding: 0 10px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
}

.picker-text {
	flex: 1;
	font-size: 14px;
	color: #333333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.picker-text.placeholder {
	color: #999999;
}

.picker-arrow {
	color: #999999;
	font-size: 12px;
	margin-left: 10px;
}

.category-input {
	width: 100%;
	height: 50px;
	background-color: #f5f5f5;
	border-radius: 8px;
	padding: 0 10px;
	font-size: 14px;
	color: #333333;
	border: none;
	outline: none;
	box-sizing: border-box;
}

.category-input::placeholder {
	color: #999999;
	font-size: 16px;
}

/* 选择器弹窗 */
.picker-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}

.picker-content {
	width: 100%;
	background-color: #ffffff;
	border-radius: 20px 20px 0 0;
	max-height: 70vh;
	display: flex;
	flex-direction: column;
}

.picker-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #f5f5f5;
}

.picker-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.picker-close {
	font-size: 24px;
	color: #999999;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.picker-body {
	flex: 1;
	overflow-y: auto;
	padding: 10px 0;
}

.picker-option {
	padding: 15px 20px;
	border-bottom: 1px solid #f5f5f5;
	color: #333333;
	font-size: 14px;
}

.picker-option.active {
	color: #ff4069;
	background-color: #fff8fa;
}

.picker-option:active {
	background-color: #f5f5f5;
}

/* 按钮容器 - 固定到最下方 */
.button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	width: 100%;
	padding: 20px 40px;
	background-color: #ffffff;
	box-sizing: border-box;
	z-index: 999;
}

.add-button {
	width: 100%;
	height: 50px;
	background-color: #ff4069;
	border-radius: 25px;
	border: none;
	color: #ffffff;
	font-size: 18px;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
}
</style>
